/*
 *  您可以更改此项目但请不要删除作者署名谢谢，否则根据中华人民共和国版权法进行处理.
 *  You may change this item but please do not remove the author's signature,
 *  otherwise it will be dealt with according to the Copyright Law of the People's Republic of China.
 *
 *  yangbuyi Copyright (c) https://yby6.com 2024.
 */


/**
 * 编写一个UUID生成
 */
export function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export const tansParams = (params) => {
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + '=';
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            const params = propName + '[' + key + ']';
            const subPart = encodeURIComponent(params) + '=';
            result += subPart + encodeURIComponent(value[key]) + '&';
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result;
};

// 方式一：使用时间戳 （时间戳版本会优先执行，点击立马执行一次）
export const throttle1 = (fn, delay = 5000) => {
  //距离上一次的执行时间
  let lastTime = 0;
  return function () {
    let _this = this;
    let _arguments = arguments;
    let now = new Date().getTime();
    //如果距离上一次执行超过了delay才能再次执行
    if (now - lastTime > delay) {
      fn.apply(_this, _arguments);
      lastTime = now;
    }
  };
};

// 方式二: 使用定时器 （定时器版本会后置执行，点击需等待delay时间之后执行）
export const thorttle2 = (fn, delay = 1000) => {
  // 接收定时器的地址
  let timer = null;
  return function () {
    let _this = this;
    let args = arguments;
    // 如果等到了delay才能执行并清空定时器
    if (!timer) {
      timer = setTimeout(function () {
        timer = null;
        fn.apply(_this, args);
      }, delay);
    }
  };
};

